#!/bin/bash
#
# Copyright (C) 2025 Masatake YAMATO <yamato@redhat.com>
#
# This file is part of util-linux.
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#

TS_TOPDIR="${0%/*}/../.."
TS_DESC="NETNSID of a namespace where no process belongs to"

. "$TS_TOPDIR"/functions.sh
ts_init "$*"

ts_check_test_command "$TS_CMD_LSNS"
ts_check_prog "ip"
ts_skip_nonroot

ts_skip_netns
ts_cd "$TS_OUTDIR"

NETNSID=$$
NS=LSNS-TEST-NETNSID-NS-FOR-PN-"$NETNSID"
NULL=/dev/null
LOG=/dev/null #/root/foo.log

function cleanup {
    ip netns delete "$NS" 2> $NULL || :
}

echo "==Cleanup" >> $LOG
cleanup

echo "==Netns ADD" >> $LOG
if ip netns add "$NS" &&
	ip netns set "$NS" "$NETNSID"; then
    echo "===Netns EXEC" >> $LOG
else
    cleanup
    ts_skip "failed to initialize"
fi

function netnsid_subtest {
    local column=$1
    local eval_func=eval_"$column"
    local O
    
    ts_init_subtest "$1"
    if O=$($TS_CMD_LSNS --raw --noheadings -Q "NETNSID == '$NETNSID'" -o $1); then
	if "$eval_func" "$O"; then
	    echo OK
	else
	    echo ERROR
	    echo "$O"
	fi
    else
	echo ERROR $?
    fi > "$TS_OUTPUT" 2>&1
    ts_finalize_subtest
}

function eval_NETNSID {
    [[ "$1" == "$NETNSID" ]]
}

function eval_TYPE {
    [[ "$1" == "net" ]]
}

function eval_NSFS {
    [[ ${1##*/} == "$NS" ]]
}

netnsid_subtest NETNSID
netnsid_subtest TYPE
netnsid_subtest NSFS

cleanup
ts_finalize

